﻿using UnityEngine;
using System.Collections;

public class SCT_TankMovement : MonoBehaviour
{
	[Range(1, 4)]
	public int bulletCount = 1;

	public float m_TurnSpeed = 30f;
	public float moveSpeed = 19.5f;
	public int currentHealth = 1500;

	public float FireRate = 0.08f;
	public float speedShell = 40f;

	public Transform Turret;
	public Transform GunEnd;

	private float nextFire;

	private Rigidbody m_Rigidbody;
	private Animator animator;

	private bool m_dead;
	public bool isTurning = false;
	public bool isTurning1 = false;

	public ParticleSystem m_smokeBarrel;
	public ParticleSystem m_tankExplosion;

	private float initialYRotation;
	private float rotationLimit = 30f;
	private float currentYRotation;
	private float targetYRotation;

	private Quaternion initialTurretLocalRotation;
	private float turnDelta = 0f;
	private float turnStopTimer = 0f;
	private float turnStopThreshold = 0.1f;

	private float turretRotationLimit = 20f;

	public ParticleSystem shengji_huangse;
	// public ParticleSystem shengji_lanse;
	public GameObject SCT_TankExplosion;

	private void Awake()
	{
		m_Rigidbody = GetComponent<Rigidbody>();

		initialYRotation = transform.eulerAngles.y;
		currentYRotation = initialYRotation;
		targetYRotation = initialYRotation;

		if (Turret != null)
			initialTurretLocalRotation = Turret.localRotation;
	}

	private void Update()
	{
		if (bulletCount > 4)
		{
			bulletCount = 4;
		}

		int num = bulletCount - 1;
		if (num > 0)
		{
			transform.Find(num.ToString()).gameObject.SetActive(false);
		}
		transform.Find(bulletCount.ToString()).gameObject.SetActive(true);
		Turret = transform.Find(bulletCount + "/root/BoneBody/GameObject");
		GunEnd = transform.Find(bulletCount + "/root/BoneBody/GameObject/BoneTurret/BoneTurretTurn/BoneBarreTilt/BoneBarrel/Barrel/GunEnd");
		m_smokeBarrel = transform.Find(bulletCount + "/root/BoneBody/GameObject/BoneTurret/BoneTurretTurn/BoneBarreTilt/BoneBarrel/Barrel/smokeBarrel").GetComponent<ParticleSystem>();
		m_tankExplosion = transform.Find(bulletCount + "/root/BoneBody/TankExplosion").GetComponent<ParticleSystem>();
		animator = transform.Find(bulletCount.ToString()).GetComponent<Animator>();

		if (m_dead) return;

		HandleRotationByTouch();

		LerpBackToInitialRotation();

		currentYRotation = targetYRotation;
		Quaternion newRot = Quaternion.Euler(0f, currentYRotation, 0f);
		m_Rigidbody.MoveRotation(newRot);

		HandleTurretRotation();

		if (isTurning1)
		{
			float currentSpeed = moveSpeed;
			Vector3 moveDirection = transform.forward * currentSpeed * Time.deltaTime;
			Vector3 newPos = m_Rigidbody.position + moveDirection;

			newPos.x = Mathf.Clamp(newPos.x, -7f, 7f);

			m_Rigidbody.MovePosition(newPos);
		}

		if (!isTurning)
		{
			animator.SetBool("TurnLeft", false);
			animator.SetBool("TurnRight", false);
		}

		if (nextFire <= 0)
		{
			nextFire = FireRate;
			FireBullets();
		}
		else
		{
			nextFire -= Time.deltaTime;
		}
	}

	private void LerpBackToInitialRotation()
	{
		float xPos = transform.position.x;

		if (!isTurning && (xPos >= 6f || xPos <= -6f))
		{
			targetYRotation = Mathf.LerpAngle(targetYRotation, initialYRotation, Time.deltaTime * 2f);
		}
	}

	private void HandleRotationByTouch()
	{
		isTurning = false;
		turnDelta = 0f;

		if (Input.touchCount == 1)
		{
			Touch touch = Input.GetTouch(0);

			if (touch.phase == TouchPhase.Moved)
			{
				float deltaX = touch.deltaPosition.x;

#if UNITY_WEBGL
				deltaX = -deltaX;
#endif
				// 根据位置衰减的转动速度
				// float factor = GetTurnSpeedFactor();
				float turnAmount = deltaX * m_TurnSpeed * 0.005f;

				turnDelta = turnAmount;
				targetYRotation += turnAmount;

				float minAngle = initialYRotation - rotationLimit;
				float maxAngle = initialYRotation + rotationLimit;

				targetYRotation = NormalizeAngle(targetYRotation);
				float minAngleNorm = NormalizeAngle(minAngle);
				float maxAngleNorm = NormalizeAngle(maxAngle);

				if (!IsAngleBetween(targetYRotation, minAngleNorm, maxAngleNorm))
				{
					if (AngleDifference(targetYRotation, minAngleNorm) < AngleDifference(targetYRotation, maxAngleNorm))
						targetYRotation = minAngleNorm;
					else
						targetYRotation = maxAngleNorm;
				}

				isTurning = true;
				turnStopTimer = 0f;
			}
			else
			{
				isTurning = false;
			}

			if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
			{
				animator.SetBool("TurnRight", false);
				animator.SetBool("TurnLeft", false);
			}
		}
		else
		{
			animator.SetBool("TurnRight", false);
			animator.SetBool("TurnLeft", false);
		}
	}

	// private float GetTurnSpeedFactor()
	// {
	// 	// 基于X轴位置线性衰减
	// 	float x = Mathf.Abs(transform.position.x);
	// 	float maxX = 7f;
	// 	float factor = Mathf.Clamp01(1f - (x / maxX));

	// 	// 保底转速因子，避免到边缘完全无法转动
	// 	float minFactor = 0.6f;
	// 	return Mathf.Max(factor, minFactor);
	// }


	private void HandleTurretRotation()
	{
		if (Turret == null) return;

		if (isTurning)
		{
			float turretTurnSpeedFactor = 0.53f;
			Turret.Rotate(0f, -turnDelta * turretTurnSpeedFactor, 0f, Space.Self);

			Vector3 localEuler = Turret.localEulerAngles;
			localEuler.y = NormalizeAngle(localEuler.y);

			if (localEuler.y > 180f)
				localEuler.y -= 360f;

			localEuler.y = Mathf.Clamp(localEuler.y, -turretRotationLimit, turretRotationLimit);

			Turret.localEulerAngles = new Vector3(localEuler.x, localEuler.y, localEuler.z);
		}
		else
		{
			turnStopTimer += Time.deltaTime;
			if (turnStopTimer >= turnStopThreshold)
			{
				Turret.localRotation = Quaternion.Lerp(Turret.localRotation, initialTurretLocalRotation, Time.deltaTime * 2f);
			}
		}
	}

	private void FireBullets()
	{
		float spacing = 0.3f;
		float startOffset = -(bulletCount - 1) * spacing / 2;

		for (int i = 0; i < bulletCount; i++)
		{
			GetComponent<AudioSource>().Play();
			Vector3 offset = Turret.right * (startOffset + i * spacing);
			Vector3 spawnPos = GunEnd.position + offset;

			GameObject shellObj = ShellPool.Instance.GetShell();
			shellObj.transform.position = spawnPos;
			shellObj.transform.rotation = Turret.rotation * Quaternion.Euler(90f, 0f, 0f);
			shellObj.name = "friendlyShell";

			ShellMove shellMove = shellObj.GetComponent<ShellMove>();
			Vector3 fireDirection = -GunEnd.up;
			shellMove.Init(fireDirection, speedShell);
		}
		m_smokeBarrel.Play();
	}

	void OnTriggerEnter(Collider col)
	{
		if (m_dead) return;

		if (col.gameObject.name == "enemyShell" || col.gameObject.name == "SCT_Block2")
		{
			SCT_Shell shell = col.GetComponent<SCT_Shell>();
			if (shell != null)
			{
				Damage(shell.shellDamage);
			}
			else
			{
				Damage(200);
			}
		}

		if (col.gameObject.tag == "prop")
		{
			bulletCount++;
			currentHealth += 100;

			shengji_huangse.Play();
			shengji_huangse.GetComponent<AudioSource>().Play();

			col.gameObject.SetActive(false);
		}
	}

	public void DestroyTank()
	{
		SCT_TankExplosion.SetActive(true);
	}

	public void Damage(int damageAmount)
	{
		currentHealth -= damageAmount;

		if (currentHealth <= 0)
		{
			m_dead = true;
			animator.enabled = true;
			animator.SetBool("Dead" + Random.Range(1, 5), true);
			Invoke("DestroyTank", 1f);

			GetComponent<BoxCollider>().enabled = false;
			gameObject.tag = "Respawn";
			Destroy(GetComponent<Rigidbody>());

			m_tankExplosion.Play();
			m_tankExplosion.gameObject.GetComponent<AudioSource>().Play();

			StartCoroutine(hideTank());
		}
	}

	private IEnumerator hideTank()
	{
		yield return new WaitForSeconds(15f);
		gameObject.SetActive(false);
	}

	private float NormalizeAngle(float angle)
	{
		angle = angle % 360f;
		if (angle < 0) angle += 360f;
		return angle;
	}

	private bool IsAngleBetween(float angle, float start, float end)
	{
		if (start <= end)
			return angle >= start && angle <= end;
		else
			return angle >= start || angle <= end;
	}

	private float AngleDifference(float a, float b)
	{
		float diff = Mathf.Abs(a - b) % 360f;
		if (diff > 180f) diff = 360f - diff;
		return diff;
	}
}
